<template>
    <div style="padding: 20px;">
        <el-scrollbar height="calc(80vh)">
            <el-form :model="formData" label-width="auto" style="max-width: 600px" ref="formRef" :rules="formRules">
                <el-form-item label="负责人" prop="ownerId">
                    <el-select
                        v-model="formData.ownerId"
                        placeholder="请选择负责人"
                        clearable
                    >
                        <el-option
                            v-for="owner in ownerOption"
                            :key="owner.id"
                            :label="owner.name"
                            :value="owner.id + ''"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="所属活动" prop="activityId">
                    <el-select
                        v-model="formData.activityId"
                        placeholder="请选择活动"
                        clearable
                    >
                        <el-option
                            v-for="activity in activityOption"
                            :key="activity.id"
                            :label="activity.name"
                            :value="activity.id + ''"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="姓名" prop="fullName">
                    <el-input v-model="formData.fullName"  clearable />
                </el-form-item>
                <el-form-item label="称呼" prop="appellation">
                    <el-select
                        v-model="formData.appellation"
                        placeholder="请选择称呼"
                        clearable
                    >
                        <el-option
                            v-for="appellation in appellationOption"
                            :key="appellation.id"
                            :label="appellation.name"
                            :value="appellation.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="手机" prop="phone">
                    <el-input v-model="formData.phone"  clearable />
                </el-form-item>
                <el-form-item label="微信" prop="weixin">
                    <el-input v-model="formData.weixin"  clearable />
                </el-form-item>
                <el-form-item label="QQ" prop="qq">
                    <el-input v-model="formData.qq"  clearable />
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="formData.email"  clearable />
                </el-form-item>
                <el-form-item label="年龄" prop="age">
                    <el-input v-model="formData.age"  clearable />
                </el-form-item>
                <el-form-item label="职业" prop="job">
                    <el-input v-model="formData.job"  clearable />
                </el-form-item>
                <el-form-item label="年收入" prop="yearIncome">
                    <el-input v-model="formData.yearIncome"  clearable />
                </el-form-item>
                <el-form-item label="住址" prop="address">
                    <el-input v-model="formData.address"  clearable />
                </el-form-item>
                <el-form-item label="贷款" prop="needLoan">
                    <el-select
                        v-model="formData.needLoan"
                        placeholder="是否需要贷款"
                        clearable
                    >
                        <el-option
                            v-for="needLoan in needLoanOption"
                            :key="needLoan.id"
                            :label="needLoan.name"
                            :value="needLoan.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="意向状态" prop="intentionState">
                    <el-select
                        v-model="formData.intentionState"
                        placeholder="意向状态"
                        clearable
                    >
                        <el-option
                            v-for="intentionState in intentionStateOption"
                            :key="intentionState.id"
                            :label="intentionState.name"
                            :value="intentionState.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="意向产品" prop="intentionProduct">
                    <el-select
                        v-model="formData.intentionProduct"
                        placeholder="意向产品"
                        clearable
                    >
                        <el-option
                            v-for="intentionProduct in intentionProductOption"
                            :key="intentionProduct.id"
                            :label="intentionProduct.name"
                            :value="intentionProduct.id + ''"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="线索状态" prop="state">
                    <el-select
                        v-model="formData.state"
                        placeholder="线索状态"
                        clearable
                    >
                        <el-option
                            v-for="state in clueStateOption"
                            :key="state.id"
                            :label="state.name"
                            :value="state.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="线索来源" prop="source">
                    <el-select
                        v-model="formData.source"
                        placeholder="线索来源"
                        clearable
                    >
                        <el-option
                            v-for="source in sourceOption"
                            :key="source.id"
                            :label="source.name"
                            :value="source.id"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="线索描述" prop="description">
                <el-input v-model="formData.description" clearable type="textarea"/>
                </el-form-item>
                <el-form-item label="下次练习时间" prop="nextContactTime">
                    <el-date-picker
                        v-model="formData.nextContactTime"
                        type="date"
                        placeholder="请选择时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        clearable
                    />
                </el-form-item>
        
                <el-form-item>
                    <el-button type="primary" @click="addOrUpdate(formRef)">提交</el-button>
                    <el-button @click="router.go(-1)">返回</el-button>
                </el-form-item>
            </el-form>
        </el-scrollbar>
    </div>
</template>
<script lang="ts" setup name="AddOrUpdateClue">
import { reactive, ref, onMounted } from 'vue'
import { Clue } from '@/hooks/clue';
import { baseService } from '@/utils/httpReqest';
import { ElMessage, valueEquals } from 'element-plus';
import type { FormRules, FormInstance } from 'element-plus';
import router from '@/router';
import { useRoute } from 'vue-router';
let formData = ref<Clue>(new Clue());
let formRef = ref();
let ownerOption = ref<any[]>([])
let activityOption = ref<any[]>([])
let appellationOption = ref<any[]>([]);
let needLoanOption = ref<any[]>([]);
let intentionStateOption = ref<any[]>([]);
let intentionProductOption = ref<any[]>([]);
let clueStateOption = ref<any[]>([]);
let sourceOption = ref<any[]>([]);
let route = useRoute();
let editId = route.params.id;
const validatePhone = (rule: any, value: any, callback: any) => {
    if (value === '') {
        callback(new Error('请输入手机号'))
        return
    }
    if (!/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确格式的中国大陆手机号'))
        return
    }
    baseService.doGet("/clue/phoneExists", {
        phone: value,
        clueId: editId
    }).then((res: any) => {
        if (res.code == 200) {
            callback();
        } else {
            callback(new Error('手机号已经存在'))
        }
    })

}
const validateWeixin = (rule: any, value: any, callback: any) => {
    if (value == '' || value == null) {
        callback()
    }
    if (!/^[a-zA-Z0-9][a-zA-Z0-9_\.]{5,19}$/.test(value)) {
        callback(new Error('请输入正确格式的微信号'))
    }
    callback();
}
const validateEmail = (rule: any, value: any, callback: any) => {
    if (value == '' || value == null) {
        callback()
    }
    if (!/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(value)) {
        callback(new Error('请输入正确格式的邮箱'))
    }
    callback();
}
const validateAge = (rule: any, value: any, callback: any) => {
    if (value == '' || value == null) {
        callback()
    }
    if (!/^(?:1[89]|[2-9][0-9]|1[01][0-9]|120)$/.test(value)) {
        callback(new Error('请输入正确的年龄'))
    }
    callback();
}
const validateYearIncome = (rule: any, value: any, callback: any) => {
    if (value == '' || value == null) {
        callback()
    }
    if (!/^(?!0(\.0+)?$)(\d+(\.\d+)?|\.\d+)$/.test(value)) {
        callback(new Error('请输入大于0的年收入'))
    }
    callback();
}
let formRules = reactive<FormRules<Clue>>({
    ownerId: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
    activityId: [{ required: true, message: '请选择活动', trigger: 'blur' }],
    phone: [{ validator: validatePhone, trigger: 'blur' }],
    weixin: [{ validator: validateWeixin, trigger: "blur" }],
    email: [{ validator: validateEmail, trigger: "blur" }],
    age: [{ validator: validateAge, trigger: "blur" }],
    yearIncome: [{ validator: validateYearIncome, trigger: "blur" }]
})
let getOwnerOption = () => {
    baseService.doGet("/user/getAllNames").then((res: any) => {
        if (res.code == 200) {
            ownerOption.value = res.data
        } else {
            ElMessage.error("获取用户用户名字列表出现错误")
        }
    })
}
let getActivityOption = () => {
    baseService.doGet("/activity/onGoingActivity").then((res: any) => {
        if (res.code == 200) {
            activityOption.value = res.data
        } else {
            ElMessage.error("获取用户用户名字列表出现错误")
        }
    })
}
let getProductOption = () => {
    baseService.doGet("/product/getNameAndId").then((res: any) => {
        if (res.code == 200) {
            intentionProductOption.value = res.data
        } else {
            ElMessage.error("获取产品列表出现错误")
        }
    })
}
let getTypeValueAndId = (typeCode: string) => {
    baseService.doGet(`/dicValue/${typeCode}`).then((res: any) => {
        if (res.code == 200) {
            switch (typeCode) {
                case "appellation":
                    appellationOption.value = res.data
                    break;
                case "needLoan":
                    needLoanOption.value = res.data
                    break;
                case "intentionState":
                    intentionStateOption.value = res.data
                    break;
                case "intentionProduct":
                    intentionProductOption.value = res.data
                    break;
                case "clueState":
                    clueStateOption.value = res.data
                    break;
                case "source":
                    sourceOption.value = res.data
                    break;
                default:
                    break;
            }
        } else {
            ElMessage.error("获取字典列表出现错误")
        }
    })
}
let clueInfo = (id: any) => {
    baseService.doGet(`/clue/clueInfo/${id}`).then((res: any) => {
        if (res.code == 200) {
            console.log(res.data);
            for (const key in res.data) {
                if (res.data[key] == '' || res.data[key] == null) {
                    formData.value[key as keyof Clue] = res.data[key]
                } else {
                    formData.value[key as keyof Clue] = (res.data[key]) + ''
                }

            }
        } else {
            ElMessage.error("获取线索信息失败")
        }
    })
}
onMounted(() => {
    getOwnerOption();
    getActivityOption();
    getTypeValueAndId('appellation')
    getTypeValueAndId('needLoan')
    getTypeValueAndId('intentionState')
    getTypeValueAndId('intentionProduct')
    getTypeValueAndId('clueState')
    getTypeValueAndId('source')
    getProductOption();
    if (editId) {
        clueInfo(editId);
    }
})
let addOrUpdate = (formRef: FormInstance) => {
    if (!formRef) return
    formRef.validate((valid) => {
        if (valid) {
            if (formData.value.id) {
                // 修改
                baseService.doPut("/clue/update", formData.value).then((res: any) => {
                    if (res.code == 200) {
                        ElMessage.success("修改成功")
                    } else {
                        ElMessage.error("修改失败")
                    }
                })
            } else {
                // 增加
                baseService.doPost("/clue/save", formData.value).then((res: any) => {
                    console.log(res);
                    if (res.code == 200) {
                        ElMessage.success("添加成功")
                    } else {
                        ElMessage.error("添加失败")
                    }
                })
            }
        }
    })

}
</script>
<style scoped></style>